*Analysis

else if "`c(username)'" == "Administrador" { 
	global ROOT "C:\Users\Administrador\Meu Drive\00 Pesquisa\# Gender Gap Turnout"
}


if "`c(username)'" == "vitor" {
    global ROOT "G:\.shortcut-targets-by-id\1Gn0Qh8ehM2EKoEEeJt9JcaQDco2Xt0O2\# Gender Gap Turnout"
}

use `"${ROOT}\Dados e Análise\TSE Data\base_tratada.dta"', clear

*1. Vote Share of each candidate in the municipality/year
egen votos_nominais_total = sum(qt_votos_nominais), by(cd_municipio ano_eleicao)
gen vote_share = qt_votos_nominais/votos_nominais_total

*2. Keep only the municipalities where the first and second highest vote totals in the first round were obtained by a man and a woman
keep if turno == 1
keep if rank == 1 | rank == 2

gen mulher = 1 if genero == "FEMININO"
replace mulher = 0 if genero == "MASCULINO"
egen auxiliar = sum(mulher), by(cd_municipio ano_eleicao)

keep if auxiliar == 1
gen auxiliar2 = 1
egen auxiliar3 = sum(auxiliar2), by(cd_municipio ano_eleicao)
drop if auxiliar3 == 1
drop auxiliar auxiliar2 auxiliar3

*3. Vote margin between the first- and second-place candidates
gen vote_share_mulher = vote_share if genero == "FEMININO"
gen vote_share_homem = vote_share if genero == "MASCULINO"
sort cd_municipio ano_eleicao rank
by cd_municipio ano_eleicao: egen auxiliar = max(vote_share_mulher)
by cd_municipio ano_eleicao: egen auxiliar2 = max(vote_share_homem)
replace vote_share_mulher = auxiliar if vote_share_mulher == .
replace vote_share_homem = auxiliar2 if vote_share_homem == .
drop auxiliar auxiliar2
gen margem = vote_share_mulher - vote_share_homem

*Order and sort
order cd_municipio ano_eleicao rank_votos qt_votos_nominais votos_nominais_total vote_share vote_share_mulher vote_share_homem mulher margem

*Label new variables
label variable votos_nominais_total "Total nominal votes in the municipality–year (first round)"
label variable vote_share "Candidate's vote share in the municipality–year (nominal / total)"
label variable mulher "Candidate is female (1 = yes)"
label variable vote_share_mulher "Vote share of the female candidate (top two, municipality–year)"
label variable vote_share_homem "Vote share of the male candidate (top two, municipality–year)"
label variable margem "Female–male vote-share margin (female - male)"

save `"${ROOT}\Dados e Análise\TSE Data\base_final.dta"', replace
